package com.bangcommunity.bbframe.sdm.validation;

import com.bangcommunity.bbframe.common.enums.BaseNumEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created by tanghc on 17/1/25.
 */
public class IsIntEnumValidator implements ConstraintValidator<IsIntEnum, Integer> {

    private Class<? extends Enum<? extends BaseNumEnum>> clazz;

    @Override
    public void initialize(IsIntEnum intVal) {
        this.clazz = intVal.clazz();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        // null values are valid
        if (value == null) {
            return true;
        }
        Enum<? extends BaseNumEnum>[] enumConstants = this.clazz.getEnumConstants();
        if (null != enumConstants && enumConstants.length > 0) {
            for (Enum<? extends BaseNumEnum> e : enumConstants) {
                BaseNumEnum baseNumEnum = (BaseNumEnum) e;
                if (null != baseNumEnum && baseNumEnum.getNum() == value) {
                    return true;
                }
            }
        }
        return false;
    }
}